import { useState } from 'react'

const initialFriends = [
  {
    id: 118836,
    name: 'Clark',
    image: 'https://img.loliapi.cn/i/pp/img105.webp',
    balance: -80
  },
  {
    id: 933372,
    name: 'Sarah',
    image: 'https://img.loliapi.cn/i/pp/img110.webp',
    balance: 80
  },
  {
    id: 499476,
    name: 'Anthony',
    image: 'https://img.loliapi.cn/i/pp/img111.webp',
    balance: 0
  }
]

function App() {
  const [friends, setFriends] = useState(initialFriends)
  const [showAddFriend, setShowAddFriend] = useState(false)
  const [selectedFriend, setSelectedFriend] = useState(null)

  function handleAddFriend(friend) {
    setFriends((prevFriends) => [...prevFriends, friend])
  }

  function handleSelectFriend(friend) {
    setSelectedFriend(cur => (cur?.id === friend.id) ? null : friend)
    setShowAddFriend(false)
  }

  function handleSplitBill(amount) {
    setFriends(friends =>
      friends.map(friend =>
        friend.id === selectedFriend.id
          ? { ...friend, balance: friend.balance + amount }
          : friend
      )
    )
  }

  return (
    <div className="app">
      <div className="sidebar">
        <FriendList friends={friends} selectedFriend={selectedFriend}
                    onSelect={handleSelectFriend}/>
        {showAddFriend && <FormAddFriend onSubmit={handleAddFriend}/>}
        <Button
          onClick={() => setShowAddFriend(!showAddFriend)}>{showAddFriend ? 'Close' : 'Add Friend'}</Button>
      </div>
      {selectedFriend && <FormSplitBill friends={friends} selectedFriend={selectedFriend}
                                        onSplitBill={handleSplitBill}/>}
    </div>
  )
}

function FriendList({ friends, onSelect, selectedFriend }) {
  return (
    <ul className="friend-list">
      {friends.map((friend) => (
        <Friend key={friend.id} friend={friend} selectedFriend={selectedFriend}
                onSelect={onSelect}/>
      ))}
    </ul>
  )
}

function Friend({ friend, onSelect, selectedFriend }) {
  const isSelected = selectedFriend && selectedFriend.id === friend.id
  return (
    <li className={isSelected ? 'selected' : ''}>
      <img crossOrigin="anonymous" src={friend.image} alt={friend.name}/>
      <h3>{friend.name}</h3>
      {friend.balance < 0 && (
        <p className="red">
          You owe {friend.name} {friend.balance}
        </p>
      )}
      {friend.balance > 0 && (
        <p className="green">
          {friend.name} owes you {friend.balance}
        </p>
      )}
      {friend.balance === 0 && <p>You are even with {friend.name}</p>}
      <Button onClick={() => onSelect(friend)}>{isSelected ? 'Close' : 'Select'}</Button>
    </li>
  )
}

function Button({ children, onClick }) {
  return <button onClick={onClick} className="button">{children}</button>
}

function FormAddFriend({ onSubmit }) {
  const random = Math.floor(Math.random() * 100)

  const [name, setName] = useState('')
  const [image, setImage] = useState(`https://img.loliapi.cn/i/pp/img${random}.webp`)

  function handleSubmit(event) {
    event.preventDefault()
    onSubmit({ id: crypto.randomUUID(), name, image, balance: 0 })
    setName('')
    setImage(`https://img.loliapi.cn/i/pp/img${random}.webp`)
  }

  return (
    <form className="form-add-friend" onSubmit={handleSubmit}>
      <label>🧑‍🤝‍🧑 Friend Name</label>
      <input value={name} onChange={(event) => setName(event.target.value)} type="text"/>

      <label>🧩 Image URL</label>
      <input value={image} onChange={(event) => setImage(event.target.value)} type="text"/>

      <Button>Add</Button>
    </form>
  )
}

function FormSplitBill({ friends, selectedFriend, onSplitBill }) {
  const [bill, setBill] = useState('')
  const [paidUser, setPaidUser] = useState('')
  const [whoIsPaying, setWhoIsPaying] = useState('user')
  const paidByFriend = bill ? bill - paidUser : ''

  function handleSubmit(event) {
    event.preventDefault()
    onSplitBill(whoIsPaying === 'user' ? paidByFriend : -paidUser)
  }

  return (
    <form className="form-split-bill" onSubmit={handleSubmit}>
      <h2>Split a bill with {selectedFriend.name}</h2>

      <label>💰 Bill value</label>
      <input value={bill} onChange={(event) => setBill(Number(event.target.value))}
             type="text"/>

      <label>🥵 Your expense</label>
      <input
        type="text"
        value={paidUser}
        onChange={(event) =>
          setPaidUser(
            Number(event.target.value) > bill ? paidUser :
              Number(event.target.value)
          )
        }
      />

      <label>👥 {selectedFriend.name}'s expense</label>
      <input value={paidByFriend} disabled type="text"/>

      <label>🤑 Who is paying the bill?</label>
      <select value={whoIsPaying} onChange={(event) => setWhoIsPaying(event.target.value)}>
        <option value="user">You</option>
        <option value="friend">{selectedFriend.name}</option>
      </select>

      <Button>Split bill</Button>
    </form>
  )
}

export default App
